package com.zyz.sunliky.service.serviceImpl;

import cn.hutool.http.HttpRequest;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.zyz.sunliky.mapper.yunshu.ChangeProjectMapper;
import com.zyz.sunliky.service.ChangeProjectService;
import com.zyz.sunliky.util.UUIDUtils;
import jakarta.transaction.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Year;
import java.util.List;
import java.util.Map;

import static com.zyz.sunliky.util.ProConstans.*;


@Service
public class ChangeProjectServiceImpl implements ChangeProjectService {

    @Value("${spring.yunshuurl}")
    private String URL;
    private static final Logger log = LoggerFactory.getLogger(ChangeProjectServiceImpl.class);
    @Autowired
    ChangeProjectMapper projectMapper;

    /**
     * 获取项目号
     *
     * @return
     */
    @Override
    public String projectNum(String projectType) {
        //projectType  项目类型
        String projectNum = "";
        String newProjectNum = "";
        String start = "";
        log.info("no");
        switch (projectType) {
            case SCJYYTS:
                projectNum = projectMapper.projectNumCP(projectType);
                start = "PD";
                newProjectNum = transform(start,projectNum,ZERO);
                break;
            case CXXP:
                projectNum = projectMapper.projectNumCP(projectType);
               // String result = projectNum.replaceAll("\\r\\n", "");
                start = "PD";
                newProjectNum = transform(start,projectNum,ONE);
                break;
            case YZXP:
                projectNum = projectMapper.projectNumCP(projectType);
                start = "PD";
                newProjectNum = transform(start,projectNum,TWO);
                break;
            case JSYYTSL:
                projectNum = projectMapper.projectNumCP(projectType);
                start = "PD";
                newProjectNum = transform(start,projectNum,THREE);
                break;
            case YYPKF:
                projectNum = projectMapper.projectNumCP(projectType);
                start = "PD";
                newProjectNum = transform(start,projectNum,FOUR);
                break;
            case GQJJ:
                projectNum = projectMapper.projectNumCP(projectType);
                start = "OP";
                newProjectNum = transform(start,projectNum,ONE);
                break;
            case GYYH:
                projectNum = projectMapper.projectNumCB(projectType);
                start = "CS";
                newProjectNum = transform(start,projectNum,ONE);
                break;
            case YYYH:
                projectNum = projectMapper.projectNumCB(projectType);
                start = "CS";
                newProjectNum = transform(start,projectNum,TWO);
                break;
            case CGYH:
                projectNum = projectMapper.projectNumCB(projectType);
                start = "CS";
                newProjectNum = transform(start,projectNum,THREE);
                break;
            case CBJY_QT:
                projectNum = projectMapper.projectNumCB(projectType);
                start = "CS";
                newProjectNum = transform(start,projectNum,FOUR);
                break;
            case SCKF:
                projectNum = projectMapper.projectNumYX(projectType);
                start = "MD";
                newProjectNum = transform(start,projectNum,ONE);
                break;
            case GLBG:
                projectNum = projectMapper.projectNumNL(projectType);
                start = "CB";
                newProjectNum = transform(start,projectNum,ONE);
                break;
            case NLJS_QT:
                projectNum = projectMapper.projectNumNL(projectType);
                start = "CB";
                newProjectNum = transform(start,projectNum,TWO);
                break;
            case GDZC:
                projectNum = projectMapper.projectNumZB(projectType);
                start = "Capex";
                newProjectNum = transform(start,projectNum,ONE);
                break;
            case GQTZ:
                projectNum = projectMapper.projectNumZB(projectType);
                start = "Capex";
                newProjectNum = transform(start,projectNum,TWO);
                break;
            case KHJF:
                projectNum = projectMapper.projectNumJF(projectType);
                start = "SP";
                newProjectNum = transform(start,projectNum,ONE);
                break;
        }
        return newProjectNum;
    }

    @Override
    public void updateStatus(String id) {
        Map map =  projectMapper.selectStatus(id);
        if (map == null) {
            throw new IllegalArgumentException("Map cannot be null");
        }
        String currentStatus = map.get("fjdmc").toString();
        String parentId = map.get("parentId").toString();

            if ("概念评估".equals(currentStatus)){
                int count =  projectMapper.updateStatusLX(parentId);
                System.out.println(count);
            }else  if ("候选品开发".equals(currentStatus)){
                int count =  projectMapper.updateStatusYXSJ(parentId);
                System.out.println(count);
            }else  if ("上市".equals(currentStatus)){
                int count =  projectMapper.updateStatusSS(parentId);
                System.out.println(count);
            }
       }
//        else {
//            if ("大试量产".equals(currentStatus)){
//                //最后一个阶段，改阶段运行状态为完成，同时项目运行状态为完成
//                int count =  projectMapper.updateProjectStatus(parentId);
//                log.info("更新了" + count + "条数据");
//            }else {
//                //当前阶段的状态为已完成，下一阶段进行中
//                int sortKey = Integer.parseInt(map.get("sortkey").toString());
//                // String sortKey = Double.toString(map.get("sortkey").toString());
//
//                int count =  projectMapper.updateStatus(parentId,sortKey);
//                log.info("更新了" + count + "条数据");
//
//            }
//        }





    @Transactional
    @Override
    public void updateMarketStatus(String id,String parentId) {
        //先判断sortkey  第二条减第一条
        //查询后判断有几条数据

        List<Map> list = projectMapper.getMarketStatus(parentId);
        if (null != list && !list.isEmpty()){
            int code   ;
            //只有一个阶段
            if (list.size() == 1){
                int count =  projectMapper.updateMarketStatus(id);
                log.info("子表更新" + count + "条数据");
                //更新主表数据
                if (count>0){
                    int count1 =  projectMapper.updateMarketState(parentId);
                    log.info("主表更新" + count1 + "条数据");
                }
            }else {
                int diff = Integer.parseInt(list.get(1).get("sortKey").toString()) -   Integer.parseInt(list.get(0).get("sortKey").toString());
                int lastIndex = list.size() - 1;
                //取最后一个阶段的值
                //int lastSortKey = Integer.parseInt(list.get(lastIndex).get("sortKey").toString());
                String lastSortKey = list.get(lastIndex).get("sortKey").toString();
                for (Map item : list) {
                    System.out.println(item);
                    if (item.get("id").equals(id)){
                        code = Integer.parseInt(item.get("sortKey").toString());
                        if (lastSortKey.equals(item.get("sortKey").toString())){
                            int count =  projectMapper.updateMarketStatus(id);
                            log.info("子表更新" + count + "条数据");
                            if (count>0){
                                int count1 =  projectMapper.updateMarketState(parentId);
                                log.info("主表更新" + count1 + "条数据");
                            }
                        }else {
                            int nextSortKey = code + diff;
                            //String strNumber = Integer.toString(number);
                            //当前阶段的状态为已完成，下一阶段进行中
                            int count =  projectMapper.updateMarket(parentId,code,nextSortKey);
                            log.info("更新了" + count + "条数据");
                        }
                    }
                }
            }
        }
    }

    /**
     * 更新资本支出节点状态
     * @param id
     * @param parentId
     */
    @Transactional
    @Override
    public void updateCapitalStatus(String id,String parentId) {
        //先判断sortkey  第二条减第一条
        //查询后判断有几条数据

        List<Map> list = projectMapper.getCapitalStatus(parentId);
        if (null != list && !list.isEmpty()){
            int code   ;
            //只有一个阶段
            if (list.size() == 1){
                //int count =  projectMapper.updateMarketStatus(id);
                int count =  projectMapper.updateCapitalStatus(id);
                log.info("子表更新" + count + "条数据");
                //更新主表数据
                if (count>0){
                    int count1 =  projectMapper.updateCapitalState(parentId);
                    log.info("主表更新" + count1 + "条数据");
                }
            }else {
                int diff = Integer.parseInt(list.get(1).get("sortKey").toString()) -   Integer.parseInt(list.get(0).get("sortKey").toString());
                int lastIndex = list.size() - 1;
                //取最后一个阶段的值
                //int lastSortKey = Integer.parseInt(list.get(lastIndex).get("sortKey").toString());
                String lastSortKey = list.get(lastIndex).get("sortKey").toString();
                for (Map item : list) {
                    System.out.println(item);
                    if (item.get("id").equals(id)){
                        code = Integer.parseInt(item.get("sortKey").toString());
                        if (lastSortKey.equals(item.get("sortKey").toString())){
                            int count =  projectMapper.updateCapitalStatus(id);
                            log.info("子表更新" + count + "条数据");
                            if (count>0){
                                int count1 =  projectMapper.updateCapitalState(parentId);
                                log.info("主表更新" + count1 + "条数据");
                            }
                        }else {
                            int nextSortKey = code + diff;
                            //String strNumber = Integer.toString(number);
                            //当前阶段的状态为已完成，下一阶段进行中
                            int count =  projectMapper.updateCapital(parentId,code,nextSortKey);
                            log.info("更新了" + count + "条数据");
                        }
                    }
                }
            }
        }
    }



    public String transform(String start,String projectNum,String first){
        //不同项目的编码规则不同
        int year = Year.now().getValue();
        String sYear = String.valueOf(year);
        System.out.println("当前年份：" + year);
        if (projectNum == null || projectNum.isEmpty() || !projectNum.contains(start)){
            return start + sYear + first;
        }
        if("Capex".equals(start)){
            projectNum = projectNum.substring(9);
        }else {
            projectNum = projectNum.substring(6);
        }
        // 字符串数字解析为整数
        int no = Integer.parseInt(projectNum);
        log.info(String.valueOf(no));
        // 项目号自增1
        int newProjectNum = ++no;
        return start + sYear + newProjectNum;
      }




      //生成子项目号
      @Override
      public String subProjectNum(String projectId,String projectType) {
          if (projectId.isBlank() || projectType.isBlank()) {
              throw new IllegalArgumentException("String cannot be null or empty");
          }
          String projectNum = "";
          if (CPKF.equals(projectType)){
              projectNum = projectMapper.subProjectNum(projectId);
          }else if (NLJS.equals(projectType)){
              projectNum = projectMapper.subProjectNumNL(projectId);
          }

          if (null == projectNum || projectNum.isBlank())
              return "GGbond";

          String result = projectNum.replaceAll("\\r\\n", "");
          String[] arrs = result.split("_");
          String subprojectNum = arrs[arrs.length - 1];
          int no = Integer.parseInt(subprojectNum);
          log.info(String.valueOf(no));
          // 项目号自增1
          int newProjectNum = ++no;
          return arrs[0] + "_" + newProjectNum;
      }

    @Override
    public BigDecimal getAmount(String code) {
        if(StringUtils.isEmpty(code)) {
            throw new RuntimeException("合同编号为空！");
        }
        BigDecimal amount = BigDecimal.ZERO;
        BigDecimal getAmount = projectMapper.getAmount(code);
        if(getAmount != null) {
            amount = getAmount;
        }
        return amount;
    }


    public String getProjectReport(String id, String tokenid) {


        String replayToken = "";
        try {
            // 发送 HTTP GET 请求并获取响应
            String response = HttpRequest.get("http://122.225.90.194:9555/api/api/runtime/form/getReplayToken")
                    .header("Accept", "application/json")
                    .header("Authorization", "Bearer " + tokenid)
                    .timeout(5000)
                    .execute()
                    .body();

            // 打印整个响应字符串
            System.out.println("Response: " + response);
            // 解析 JSON 响应
            JsonObject jsonObject = JsonParser.parseString(response).getAsJsonObject();

            // 获取名为"data"的字段的值
            replayToken = jsonObject.get("data").getAsString();

            // 打印 data 字段的值
            System.out.println("replayToken: " + replayToken);
        } catch (Exception e) {
            // 捕获可能的异常
            e.printStackTrace();
        }

        /**查询表头**/
        List<Map<String,Object>> headList = projectMapper.findHeadList(id);
        if(headList.isEmpty())throw new RuntimeException("没有此单据!");
        JSONObject object = new JSONObject();
        object.put("replayToken", replayToken);
        object.put("sheetCode", "project_report");
        // 添加workflowInstanceId字段，并将其值设为空字符串
        object.put("workflowInstanceId", null);  // 添加workflowInstanceId字段，并将其值设为空字符串
        object.put("workflowCode", "project_report");
        object.put("workItemId", null);
        String getuuid = UUIDUtils.getuuid();
        JSONObject data=new JSONObject();
        Map map = headList.get(0);
        data.put("id", getuuid);
        map.forEach((key,value)->{
            data.put(String.valueOf(key),value);
        });
        JSONArray array=new JSONArray();
        data.put("sales_price_details",array);
        JSONObject bizObject=new JSONObject();
        bizObject.put("schemaCode","model_yfxmjdhb");
        bizObject.put("sheetCode","model_yfxmjdhb");
        bizObject.put("workflowInstanceId",null);
        bizObject.put("data",data);
        object.put("bizObject",bizObject);
        //object.put("replayToken",replayToken);
        System.out.println(data);
        String s = object.toJSONString();
        String postResult = HttpRequest
                .post(URL+"/api/api/runtime/form/save")
                .header("Content-Type","application/json")
                .header("Authorization", "Bearer "+ tokenid)
                .body(s)
                .execute()
                .body();
//        updateRequestNo(getuuid);
        System.out.println(s);
        System.out.println(postResult);
        // JsonObject jsonObject = JsonParser.parseString(postResult).getAsJsonObject();

        return postResult;
    }
}
